<?php

require_once("facebook.php");

$config = array();
$config['appId'] = '404338142994672';
$config['secret'] = 'cc4ed4fa218605a1a1bab05b1ca7f345';
$config['fileUpload'] = false; // optional

// set_include_path('/home/freshbuzzing/www/140dev/db');
// set_include_path('/home/freshbuzzing/www/log');
//set_include_path('/Library/WebServer/Documents/140dev/db');


define('__ROOT__', dirname(dirname(__FILE__))); 
require('/home/freshbuzzing/www/140dev/db/140dev_config.php'); 
require('/home/freshbuzzing/www/140dev/db/db_lib.php'); 

//set_include_path('/Library/WebServer/Documents/log');

require('/home/freshbuzzing/www/log/logging.php'); 

$oDB = new db;

if(!$oDB)
{
	die('Could not connect: ' . mysql_error());
}

$logging = new Logging;
$result_log = 'OK';
$num_proceso = $logging->init_log("FACEBOOK - REGISTRO FEEDS");
	
$facebook = new Facebook($config);

$result = $oDB->select("SELECT DS_USER_FB, ID_USER_FB FROM MAST_FACEBOOK_ACCOUNTS WHERE BL_PARSE = 1 AND DS_USER_FB='NHHoteles' ORDER BY DS_USER_FB ASC");
		
$cont_reg = 0;
while($row = mysqli_fetch_row($result))
{		
	$id_fb_account = $row[0];
	$id_num_fb_account = $row[1];
	$cont_reg = $cont_reg + 1;
	
	$hoy = strtotime("-1 month");
	$since = date("Y-m-d",$hoy); 
	$url = 	$id_fb_account . '/feed?since=' . $since;
	
	
	$mas_paginas = true;
	while($mas_paginas){
		$pageFeed = $facebook->api($url);
		foreach($pageFeed['data'] as $feed){
		$id = $feed['id'];
			
		if(isset($feed['message']))
			$message = str_replace("'","''",$feed['message']);
		else
			$message = "";
			
		if(isset($feed['story']))
			$story = str_replace("'","''",$feed['story']);
		else
			$story = "";
			
		if(isset($feed['picture']))
			$picture = $feed['picture'];
		else
			$picture = "";
		
		if(isset($feed['link']))
			$link = $feed['link'];
		else
			$link = "";
			
		if(isset($feed['type']))
			$type = $feed['type'];
		else
			$type = "";
			
		if(isset($feed['status_type']))
			$status_type = $feed['status_type'];
		else
			$status_type = "";
		
		if(isset($feed['object_id']))
			$object_id = $feed['object_id'];
		else
			$object_id = "";
			
		$dTime = strtotime($feed['created_time']);
		$created_time = date("Y-m-d H:i",$dTime);
		$dTime = strtotime($feed['updated_time']);
		$updated_time = date("Y-m-d H:i",$dTime);
		
		if(isset($feed['likes'])){
			$likes = $feed['likes'];
			if(count($likes) > 0){
				$likes_nro = $likes['count'];
				// Obtengo los nombres de los usuarios
				/*
				foreach($feed['data'] as $user){
					$user_name = $user['name'];
					$user_id = $user['id'];
					if($oDB->in_table('MAST_FACEBOOK_USERS',"ID_USER_FB='" . $user_id . "'"))
					{	
						$values = "DS_NAME='" . $user_name . "'";
						$oDB->update('MAST_FACEBOOK_USERS',$values,"ID_USER_FB='" . $user_id. "'");
					}
					else
					{
						$values = "ID_USER_FB='" . $user_id . "', DS_NAME='" . $user_name . "', DS_URL_PICTURE=''";
					
						$oDB->insert('MAST_FACEBOOK_USERS',$values);
					}
				}*/
			}
		}
		else
			$likes_nro = 0;
		
		if(isset($feed['comments'])){	
			$comments = $feed['comments'];
			if(count($comments) > 0){
				$comments_nro = count($comments['data']);
			}
		}
		else
			$comments_nro = 0;
			
		if(isset($feed['shares'])){
			$shares = $feed['shares'];
			if(count($shares) > 0)		
				$shares_nro = $shares['count'];
		}
		else
			$shares_nro = 0;
			
		try{				
				if($oDB->in_table('MAST_FACEBOOK_POSTS',"ID_FB_POST='" . $id . "'"))
				{	
					$values = "NUM_LIKES=" . $likes_nro . ",NUM_COMMENTS=" . $comments_nro . ",NUM_SHARES=" . $shares_nro;
					$oDB->update('MAST_FACEBOOK_POSTS',$values,"ID_FB_POST='" . $id. "'");
				}
				else
				{
					$values = "ID_FB_POST='" . $id . "', DS_MESSAGE='" . $message . "', DS_STORY='" . $story . "', DS_PICTURE='" . $picture . "', DS_LINK='" . $link . "', DS_TYPE = '" . $type . "', DS_STATUS_TYPE='" . $status_type . "', ID_FB_OBJECT='" . $object_id . "', DT_CREATED_TIME='" . $created_time . "', DT_UPDATED_TIME='" . $updated_time . "', NUM_LIKES=" . $likes_nro . ", NUM_COMMENTS=" . $comments_nro . ", NUM_SHARES=" . $shares_nro . ", ID_FB_ACCOUNT = '" . $id_num_fb_account . "'";
					
					$oDB->insert('MAST_FACEBOOK_POSTS',$values);
				}
		}
		catch(Exception $e){
			log_details($num_proceso,"ERROR: " . $e->getMessage());
		}
	}	
		$mas_paginas = false;
		
		if(isset($pageFeed['paging'])){
			if(isset($pageFeed['paging']['next'])){
				$url = $pageFeed['paging']['next'] . "&since=" . $since;
				$url = str_replace("https://graph.facebook.com/","",$url);
				$mas_paginas = true;
			}
		}	
	}
	
}
$logging->end_log($num_proceso, "Se han consultado " . $cont_reg . " cuentas de Facebook de restaurantes",$result_log);
/*
print_r("<pre>");
	print_r($pageFeed);
	print_r("</pre>");
*/

/*
// Get User ID
$user = $facebook->getUser();


if ($user) {
  try {
    // Proceed knowing you have a logged in user who's authenticated.
    $user_profile = $facebook->api('/me','GET');
	echo "Name: " . $user_profile['name'];
 } catch (FacebookApiException $e) {
     $login_url = $facebook->getLoginUrl(); 
     echo 'Please eg <a href="' . $login_url . '">login.</a>';
     error_log($e->getType());
     error_log($e->getMessage());
  }
}
else{
	// No user, print a link for the user to login
	$params = array(
  'scope' => 'read_stream, friends_likes'
	);
      $login_url = $facebook->getLoginUrl($params);
      echo 'Please <a href="' . $login_url . '">login.</a>';
}
*/
?>